<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>20210902124邵文杰</title>
</head>

<body>
    <label for="inchInput">英寸:</label>
    <input type="number" id="inchInput">
    <label for="mmInput">毫米:</label>
    <input type="number" id="mmInput">
    <p>【英寸】修改前值为: <span id="beforeInchValue"></span>，【英寸】修改后值为: <span id="afterInchValue"></span></p>
    <script>
        const inchInput = document.getElementById('inchInput');
        const mmInput = document.getElementById('mmInput');
        const beforeInchValue = document.getElementById('beforeInchValue');
        const afterInchValue = document.getElementById('afterInchValue');
        let originalInchValue = "";
        let originalMmValue = "";

        // 英寸转毫米的换算比例
        const inchToMm = 25.4;

        // 监听英寸输入框的变化
        inchInput.addEventListener('input', function () {
            const prevInchValue = originalInchValue; // 保存之前的英寸值
            if (inchInput.value === "") {
                beforeInchValue.textContent = prevInchValue;
            } else {
                beforeInchValue.textContent = prevInchValue;
            }
            const inchValue = parseFloat(inchInput.value);
            if (!isNaN(inchValue)) {
                afterInchValue.textContent = inchInput.value;
                originalInchValue = inchInput.value;
                const mmValue = inchValue * inchToMm;
                mmInput.value = mmValue.toFixed(2);
            } else {
                mmInput.value = "";
                afterInchValue.textContent = "";
            }
        });

        // 监听毫米输入框的变化
        mmInput.addEventListener('input', function () {
            const prevMmValue = originalMmValue; // 保存之前的毫米值
            if (mmInput.value === "") {
                beforeInchValue.textContent = prevMmValue / inchToMm;
            } else {
                beforeInchValue.textContent = prevMmValue / inchToMm;
            }
            const mmValue = parseFloat(mmInput.value);
            if (!isNaN(mmValue)) {
                afterInchValue.textContent = mmInput.value / inchToMm;
                originalMmValue = mmInput.value / inchToMm;
                const inchValue = mmValue / inchToMm;
                inchInput.value = inchValue.toFixed(2);
            } else {
                inchInput.value = "";
                afterInchValue.textContent = "";
            }
        });
    </script>
</body>

</html>